import React, { useState, useEffect } from 'react'
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons'
import { message, Upload } from 'antd'
import type { GetProp, UploadProps } from 'antd'
import config from '@/config'
import useUserStore from '@/store/user'

type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0]

interface IProps {
  onUploadChange: (url: string) => void
  photo?: string // 可选属性，用于传递父组件的图片地址
}

const getBase64 = (img: FileType, callback: (url: string) => void) => {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}

const beforeUpload = (file: FileType) => {
  console.log(file)

  const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
  if (!isJpgOrPng) {
    message.error('只能上传jpg和png的图片!')
  }
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    message.error('图片大于2MB!')
  }
  return isJpgOrPng && isLt2M
}

// 修复类型不匹配问题，为 React.FC 指定 IProps 类型
const MyUpload: React.FC<IProps> = (props) => {
  const [loading, setLoading] = useState(false)
  const [imageUrl, setImageUrl] = useState<string>()
  const { token } = useUserStore()
  const handleChange: UploadProps['onChange'] = (info) => {
    console.log(info)

    if (info.file.status === 'uploading') {
      setLoading(true)
      return
    }
    if (info.file.status === 'done') {
      //Get this url from response in real world.
      getBase64(info.file.originFileObj as FileType, (url) => {
        console.log(info.file.response.data)
        setLoading(false)
        setImageUrl(url)
        //将图片地址传递给父组件
        props.onUploadChange(info.file.response.data)
      })
    }
  }

  const uploadButton = (
    <button style={{ border: 0, background: 'none' }} type="button">
      {loading ? <LoadingOutlined /> : <PlusOutlined />}
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  )

  //接受父组件传递的图片地址
  useEffect(() => {
    if (props.photo) {
      setImageUrl(config.imgUrl + props.photo)
    }
  }, [props.photo])

  return (
    <Upload
      name="file"
      listType="picture-card"
      className="avatar-uploader"
      showUploadList={false}
      action={config.uploadUrl + '/api/Goods/UplodaImg'}
      headers={{
        Authorization: 'Bearer ' + token
      }}
      beforeUpload={beforeUpload}
      onChange={handleChange}
    >
      {imageUrl ? (
        <img
          src={imageUrl}
          alt="avatar"
          style={{ width: '100%', height: '100%' }}
        />
      ) : (
        uploadButton
      )}
    </Upload>
  )
}

export default MyUpload
